<template>
  <nav-bar />
  <view class="scrap-page">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <text class="nav-back" @click="onBack">&#8592;</text>
      <text class="nav-title">编辑报废记录</text>
    </view>

    <!-- 多图横向滚动 -->
    <scroll-view 
      class="scrap-img-list-horizontal" 
      scroll-x 
      :scroll-with-animation="true"
      :enhanced="true"
      :show-scrollbar="false"
      :bounces="true"
    >
      <view class="img-list-row">
        <view class="img-box-horizontal" v-for="(img, index) in images" :key="index">
          <image class="scrap-img-horizontal" :src="IntranetConfig.domain + img" mode="aspectFill" />
          <view class="img-delete-horizontal" @click="deleteImage(index)">×</view>
        </view>
        <!-- 上传按钮 -->
        <view class="img-box-horizontal add-img-horizontal" @click="chooseImage" v-if="images.length < 9">
          <text class="add-icon-horizontal">+</text>
        </view>
      </view>
    </scroll-view>

    <!-- 表单区域 -->
    <view class="form-section">
      <view class="form-item required">
        <view class="label">商品</view>
        <picker class="value-picker" :range="productList" range-key="name" @change="onProductChange">
          <view class="picker-value">{{ selectedProduct ? selectedProduct.name : '请选择' }}</view>
        </picker>
      </view>

      <view class="form-item required">
        <view class="label">报废位置</view>
        <view class="location-options">
          <view 
            class="location-option" 
            :class="{ active: scrapLocation === 1 }"
            @click="setLocation(1)"
          >
            货架
          </view>
          <view 
            class="location-option" 
            :class="{ active: scrapLocation === 2 }"
            @click="setLocation(2)"
          >
            仓库
          </view>
        </view>
      </view>

      <view class="form-item required">
        <view class="label">报废数量</view>
        <view class="value-row">
          <input class="value-input" v-model="scrapNumber" type="number" placeholder="请输入" />
          <text class="unit">个</text>
        </view>
      </view>

      <view class="form-item required" @click="showReasonPopup">
        <view class="label">报废原因</view>
        <view class="value-row description-preview">
          <text class="description-text">{{ scrapReason || '请输入' }}</text>
          <text class="arrow">></text>
        </view>
      </view>
    </view>

    <!-- 报废原因弹窗 -->
    <uni-popup ref="reasonPopup" type="center">
      <view class="description-popup">
        <view class="popup-header">
          <text class="popup-title">报废原因</text>
          <text class="popup-close" @click="closeReasonPopup">×</text>
        </view>
        <view class="popup-content">
          <view class="history-section" v-if="reasonHistory.length > 0">
            <view class="history-title">历史记录</view>
            <scroll-view class="history-list" scroll-y>
              <view 
                class="history-item" 
                v-for="(item, index) in reasonHistory" 
                :key="index"
                @click="useHistoryReason(item)"
              >
                <text class="history-text">{{ item }}</text>
                <text class="history-delete" @click.stop="deleteHistoryReason(index)">×</text>
              </view>
            </scroll-view>
          </view>
          <textarea 
            class="description-textarea" 
            v-model="scrapReason" 
            placeholder="请输入报废原因"
            :maxlength="200"
            show-confirm-bar="false"
          />
          <view class="word-count">{{ scrapReason.length }}/200</view>
        </view>
        <view class="popup-footer">
          <button class="confirm-btn" @click="closeReasonPopup">确定</button>
        </view>
      </view>
    </uni-popup>

    <!-- 底部按钮 -->
    <view class="footer-bar">
      <button class="save-btn" @click="submitForm">更新</button>
    </view>

    <!-- 消息框组件 -->
    <message-box
      v-model="showMsgBox"
      :title="msgBoxTitle"
      :content="msgBoxContent"
      :showCancel="msgBoxShowCancel"
      :confirmText="msgBoxConfirmText"
      :cancelText="msgBoxCancelText"
      @confirm="onMsgBoxConfirm"
      @cancel="onMsgBoxCancel"
    />

    <!-- Toast 组件 -->
    <toast
      v-model="showToast"
      :content="toastContent"
      :type="toastType"
      :duration="toastDuration"
    />
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { IntranetConfig, UserConfig } from '@/static/js/config'
import MessageBox from '@/components/message-box/message-box.vue'
import Toast from '@/components/toast/toast.vue'

// 获取用户信息
const userInfo = computed(() => UserConfig.getUserInfo())

// Toast 相关
const showToast = ref(false)
const toastContent = ref('')
const toastType = ref('')
const toastDuration = ref(2000)

function showCustomToast(content, type = '', duration = 2000) {
  toastContent.value = content
  toastType.value = type
  toastDuration.value = duration
  showToast.value = true
}

// 消息框相关
const showMsgBox = ref(false)
const msgBoxTitle = ref('')
const msgBoxContent = ref('')
const msgBoxShowCancel = ref(true)
const msgBoxConfirmText = ref('确定')
const msgBoxCancelText = ref('取消')
let msgBoxCallback = null

function openMsgBox({ title = '', content = '', showCancel = true, confirmText = '确定', cancelText = '取消', callback = null }) {
  msgBoxTitle.value = title
  msgBoxContent.value = content
  msgBoxShowCancel.value = showCancel
  msgBoxConfirmText.value = confirmText
  msgBoxCancelText.value = cancelText
  msgBoxCallback = callback
  showMsgBox.value = true
}

function onMsgBoxConfirm() {
  if (msgBoxCallback) msgBoxCallback(true)
}

function onMsgBoxCancel() {
  if (msgBoxCallback) msgBoxCallback(false)
}

// 表单数据
const productList = ref([])
const selectedProduct = ref(null)
const scrapNumber = ref('')
const scrapLocation = ref(1)
const scrapReason = ref('')
const images = ref([])
const scrapId = ref('')

// 原因弹窗
const reasonPopup = ref(null)
const reasonHistory = ref([])
const MAX_HISTORY_COUNT = 10

// 获取报废记录详情
async function getScrapDetail(id) {
  try {
    const res = await uni.request({
      url: `${IntranetConfig.domain}api/scrap/get_scrap/${id}/`,
      method: 'GET',
      header: IntranetConfig.headers
    })

    if (res.data.code === 200) {
      const data = res.data.data
      selectedProduct.value = data.product
      scrapNumber.value = data.scrap_number
      scrapLocation.value = data.scrap_location
      scrapReason.value = data.scrap_reason
      images.value = data.images.map(img => img.image)
    } else {
      showCustomToast(res.data.msg || '获取报废记录失败', 'error')
    }
  } catch (error) {
    showCustomToast('获取报废记录失败', 'error')
  }
}

// 获取商品列表
async function getProductList() {
  try {
    const res = await uni.request({
      url: `${IntranetConfig.domain}api/product/get_product_list/`,
      method: 'GET',
      header: IntranetConfig.headers
    })

    if (res.data.code === 200) {
      productList.value = res.data.data
    }
  } catch (error) {
    showCustomToast('获取商品列表失败', 'error')
  }
}

// 选择商品
function onProductChange(e) {
  const index = e.detail.value
  selectedProduct.value = productList.value[index]
}

// 设置报废位置
function setLocation(location) {
  scrapLocation.value = location
}

// 选择图片
async function chooseImage() {
  try {
    const res = await uni.chooseImage({
      count: 9 - images.value.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    })

    images.value = [...images.value, ...res.tempFilePaths]
  } catch (error) {
    console.error('选择图片失败:', error)
  }
}

// 删除图片
function deleteImage(index) {
  images.value.splice(index, 1)
}

// 原因弹窗
function showReasonPopup() {
  reasonPopup.value.open()
}

function closeReasonPopup() {
  // 如果原因不为空且不在历史记录中，则添加到历史记录
  if (scrapReason.value && !reasonHistory.value.includes(scrapReason.value)) {
    reasonHistory.value.unshift(scrapReason.value)
    // 保持历史记录数量不超过最大值
    if (reasonHistory.value.length > MAX_HISTORY_COUNT) {
      reasonHistory.value.pop()
    }
    saveReasonHistory()
  }
  reasonPopup.value.close()
}

// 使用历史原因
function useHistoryReason(reason) {
  scrapReason.value = reason
}

// 删除历史原因
function deleteHistoryReason(index) {
  reasonHistory.value.splice(index, 1)
  saveReasonHistory()
}

// 保存历史记录到本地存储
function saveReasonHistory() {
  uni.setStorageSync('reasonHistory', JSON.stringify(reasonHistory.value))
}

// 返回上一页
function onBack() {
  uni.navigateBack()
}

// 提交表单
function submitForm() {
  if (!selectedProduct.value) {
    showCustomToast('请选择商品', 'error')
    return
  }

  if (!scrapNumber.value) {
    showCustomToast('请输入报废数量', 'error')
    return
  }

  if (!scrapReason.value) {
    showCustomToast('请输入报废原因', 'error')
    return
  }

  openMsgBox({
    title: '确认更新',
    content: '确定要更新这条报废记录吗？',
    callback: async (confirmed) => {
      if (confirmed) {
        try {
          // 先上传图片
          const uploadedImages = []
          for (const image of images.value) {
            if (image.startsWith('http')) {
              uploadedImages.push(image)
              continue
            }
            const uploadRes = await uni.uploadFile({
              url: `${IntranetConfig.domain}api/upload/`,
              filePath: image,
              name: 'file',
              header: IntranetConfig.headers
            })
            const data = JSON.parse(uploadRes.data)
            if (data.code === 200) {
              uploadedImages.push(data.data.url)
            }
          }

          // 更新报废记录
          const res = await uni.request({
            url: `${IntranetConfig.domain}api/scrap/update_scrap/${scrapId.value}/`,
            method: 'PUT',
            header: IntranetConfig.headers,
            data: {
              product_id: selectedProduct.value.id,
              scrap_number: scrapNumber.value,
              scrap_location: scrapLocation.value,
              scrap_reason: scrapReason.value,
              images: uploadedImages
            }
          })

          if (res.data.code === 200) {
            showCustomToast('更新成功', 'success')
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          } else {
            showCustomToast(res.data.msg || '更新失败', 'error')
          }
        } catch (error) {
          showCustomToast('更新失败', 'error')
        }
      }
    }
  })
}

// 检查权限
function checkPermission() {
  if (!userInfo.value) {
    showCustomToast('请先登录', 'error')
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/login/login'
      })
    }, 1500)
    return false
  }

  if (userInfo.value.is_superuser !== 1 && userInfo.value.is_superuser !== 2) {
    showCustomToast('您没有报废权限', 'error')
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
    return false
  }

  return true
}

// 页面加载
onMounted(() => {
  if (checkPermission()) {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const id = currentPage.options.id
    if (id) {
      scrapId.value = id
      getScrapDetail(id)
      getProductList()
      // 从本地存储加载历史记录
      const history = uni.getStorageSync('reasonHistory')
      if (history) {
        reasonHistory.value = JSON.parse(history)
      }
    } else {
      showCustomToast('参数错误', 'error')
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  }
})
</script>

<style lang="scss" scoped>
.scrap-page {
  background: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  overflow-x: hidden;
  max-width: 100vw;
  box-sizing: border-box;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  height: 96rpx;
  background: #fff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
  
  .nav-back { 
    color: #333; 
    font-size: 44rpx;
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s;
    
    &:active {
      background: rgba(0, 0, 0, 0.05);
    }
  }
  
  .nav-title { 
    flex: 1; 
    text-align: center; 
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
  }
}

.scrap-img-list-horizontal {
  width: 100%;
  overflow-x: auto;
  padding: 32rpx;
  background: #fff;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
  max-width: 100vw;
}

.img-list-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 8rpx 0;
  box-sizing: border-box;
  max-width: 100vw;
}

.img-box-horizontal {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  margin-right: 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  transition: all 0.3s;
  
  &:active {
    transform: scale(0.98);
  }
  
  .scrap-img-horizontal {
    width: 160rpx;
    height: 160rpx;
    border-radius: 16rpx;
    object-fit: cover;
  }
  
  .img-delete-horizontal {
    position: absolute;
    top: -16rpx;
    right: -16rpx;
    width: 44rpx;
    height: 44rpx;
    background: #ff7e2d;
    color: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    font-weight: bold;
    box-shadow: 0 4rpx 12rpx rgba(255, 126, 45, 0.3);
    z-index: 2;
    transition: all 0.3s;
    
    &:active {
      transform: scale(0.9);
      background: darken(#ff7e2d, 5%);
    }
  }
}

.add-img-horizontal {
  width: 160rpx;
  height: 160rpx;
  border-radius: 16rpx;
  border: 2rpx dashed #ff7e2d;
  background: #fff6ed;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  
  &:active {
    transform: scale(0.98);
    background: darken(#fff6ed, 2%);
  }
  
  .add-icon-horizontal {
    font-size: 56rpx;
    color: #ff7e2d;
    font-weight: bold;
  }
}

.form-section {
  margin: 24rpx 32rpx;
  background: #fff;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
  box-sizing: border-box;
  max-width: 100vw;
  
  .form-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx;
    border-bottom: 1rpx solid #f5f5f5;
    font-size: 30rpx;
    transition: all 0.3s;
    
    &:active {
      background: #fafafa;
    }
    
    &:last-child {
      border-bottom: none;
    }
    
    .label {
      color: #333;
      width: 180rpx;
      text-align: left;
      flex-shrink: 0;
      font-weight: 500;
    }
    
    .value-input {
      flex: 1;
      min-width: 0;
      border: none;
      background: transparent;
      font-size: 30rpx;
      color: #333;
      text-align: right;
      padding: 0;
      
      &::placeholder {
        color: #999;
      }
    }
    
    .value-picker {
      flex: 1;
      text-align: right;
      
      .picker-value {
        color: #333;
        font-size: 30rpx;
        
        &:empty::before {
          content: '请选择';
          color: #999;
        }
      }
    }
    
    .value-row {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      min-width: 0;
    }
    
    .unit {
      color: #666;
      font-size: 26rpx;
      margin-left: 8rpx;
    }
    
    .arrow {
      color: #999;
      font-size: 28rpx;
      margin-left: 8rpx;
    }
  }
  
  .form-item.required .label:after {
    content: '*';
    color: #ff7e2d;
    margin-left: 4rpx;
  }
}

.description-preview {
  .description-text {
    flex: 1;
    color: #333;
    font-size: 30rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 400rpx;
    
    &:empty::before {
      content: '请输入';
      color: #999;
    }
  }
}

.description-popup {
  width: 90vw;
  max-width: 600rpx;
  background: #fff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  
  .popup-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx;
    border-bottom: 1rpx solid #f5f5f5;
    background: #fff;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
    
    .popup-close {
      font-size: 40rpx;
      color: #999;
      padding: 16rpx;
      margin: -16rpx;
      border-radius: 50%;
      transition: all 0.3s;
      
      &:active {
        background: #f5f5f5;
      }
    }
  }
  
  .popup-content {
    padding: 32rpx;
    background: #fff;
    
    .history-section {
      margin-bottom: 24rpx;
      
      .history-title {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 16rpx;
      }
      
      .history-list {
        max-height: 200rpx;
        margin-bottom: 16rpx;
        
        .history-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 16rpx;
          background: #f8f9fa;
          border-radius: 12rpx;
          margin-bottom: 12rpx;
          transition: all 0.3s;
          
          &:active {
            background: #f0f1f2;
          }
          
          .history-text {
            flex: 1;
            font-size: 28rpx;
            color: #333;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-right: 16rpx;
          }
          
          .history-delete {
            width: 40rpx;
            height: 40rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 32rpx;
            border-radius: 50%;
            transition: all 0.3s;
            
            &:active {
              background: rgba(0, 0, 0, 0.05);
              color: #666;
            }
          }
        }
      }
    }
    
    .description-textarea {
      width: 100%;
      height: 400rpx;
      font-size: 30rpx;
      line-height: 1.6;
      color: #333;
      padding: 24rpx;
      background: #f8f9fa;
      border-radius: 16rpx;
      border: 1rpx solid #eee;
      box-sizing: border-box;
      
      &::placeholder {
        color: #999;
      }
    }
    
    .word-count {
      text-align: right;
      font-size: 24rpx;
      color: #999;
      margin-top: 16rpx;
    }
  }
  
  .popup-footer {
    padding: 24rpx 32rpx;
    border-top: 1rpx solid #f5f5f5;
    background: #fff;
    
    .confirm-btn {
      width: 100%;
      height: 88rpx;
      background: #ff7e2d;
      color: #fff;
      border: none;
      border-radius: 12rpx;
      font-size: 32rpx;
      font-weight: 500;
      transition: all 0.3s;
      
      &:active {
        transform: scale(0.98);
        background: darken(#ff7e2d, 5%);
      }
    }
  }
}

.footer-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 24rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
  
  .save-btn {
    width: 100%;
    height: 88rpx;
    background: #ff7e2d;
    color: #fff;
    border: none;
    border-radius: 12rpx;
    font-size: 32rpx;
    font-weight: 500;
    transition: all 0.3s;
    
    &:active {
      transform: scale(0.98);
      background: darken(#ff7e2d, 5%);
    }
  }
}
</style> 